package com.winter.iterator;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

/**
 * @program: Collection
 * @description: 测试Vector遍历方式的效率
 * @author: Mr.Liang
 * @create: 2018-01-12 09:54
 **/
public class VectorIterator {
    public static void main(String[] args) {
        Vector<Object> vector = new Vector<>();
        for (int i = 0; i < 100000; i++) {
            vector.add(i);
        }
//        随机访问遍历
        vectorRandomAccess(vector);
//        迭代器遍历
        vectorIterator(vector);
//        foreach遍历
        vectorForeach(vector);
//        Numeration遍历
        vectorNumeration(vector);
    }


    private static void vectorIterator(Vector<Object> vector) {
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        Iterator<Object> iterator = vector.iterator();
        while (iterator.hasNext()) {
            iterator.next();
        }
        endTime = System.currentTimeMillis();
        long value = endTime - startTime;
        System.out.println("Iterator遍历" + value + "ms");
    }

    private static void vectorRandomAccess(Vector<Object> vector) {
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        for (int i = 0; i < vector.size(); i++) {
            vector.get(i);
        }
        endTime = System.currentTimeMillis();
        long value = endTime - startTime;
        System.out.println("RandomAccess遍历" + value + "ms");
    }

    private static void vectorForeach(Vector<Object> vector) {
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        for (Object one : vector
                )
            ;
        endTime = System.currentTimeMillis();
        long value = endTime - startTime;
        System.out.println("Foreach遍历" + value + "ms");
    }

    private static void vectorNumeration(Vector<Object> vector) {
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        Enumeration<Object> elements = vector.elements();
        while (elements.hasMoreElements()) {
            elements.nextElement();
        }
        endTime = System.currentTimeMillis();
        long value = endTime - startTime;
        System.out.println("Numeration遍历" + value + "ms");
    }
}
